package com.ruoyi.hospital.utils;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hospital.entity.LoginHospital;
import com.ruoyi.hospital.service.HospitalTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 用户端token过滤器 验证token有效性
 * 
 * @author ZDL
 */
@Component
public class HospitalTokenFilter
{
    @Autowired
    private HospitalTokenService tokenService;

    public boolean doFilterInternal(HttpServletRequest request)
            throws ServletException, IOException
    {
        LoginHospital loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            return true;
        }
        return false;
    }
}
